package hr.fer.zpr.nmbp.project2.dao;

import hr.fer.zpr.nmbp.project2.dao.exceptions.PrimaryKeyConstraintException;
import hr.fer.zpr.nmbp.project2.model.Karton;

import java.util.List;
import java.util.Properties;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;

public class KartonDAO {

	private Session session;

    public KartonDAO(Session session) {
        this.session = session;
    }
	
	public void save(Karton karton) {
		
		if(karton.getPacijent() == null){
			throw new PrimaryKeyConstraintException("Karton mora imati dodijeljenog pacijenta");
		}
		
    	Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.saveOrUpdate(karton);
            tx.commit();
        } catch (ConstraintViolationException e) {
            if (tx != null) tx.rollback();
            throw new PrimaryKeyConstraintException("Karton za pacijenta već postoji u bazi podataka");
        }
    }
        

    public List<Karton> load(Karton kartonPrototype) {
        Properties prop = new Properties();
        StringBuilder sb = new StringBuilder();
        sb.append("select k from Karton as k");
        if (kartonPrototype.getPacijentMbo() != null) {
            sb.append(" where k.pacijentMbo = :mbo");
            prop.put("mbo", kartonPrototype.getPacijentMbo());
        }
                                        
        return (List<Karton>) session.createQuery(sb.toString()).setProperties(prop).list();
    }
    
    public List<Karton> loadAll() {
        return (List<Karton>) session.createQuery("select k from Karton as k").list();
    }

}
